import threading
import time
import serial
from Debug import error, debug

class SerialIntermec():
    
    def __init__(self, port, baudrate = 9600, bytesize = 8, parity = 'N', stopbits = 1):
        self.serial = serial.Serial(port, baudrate, bytesize, parity, stopbits)
        self.alive = False
        self.CheckData = None
        
    def Start(self):
        if not self.serial:
            self.serial.open()
            
        if self.serial.isOpen():
            self.alive = True
            self.readthread = threading.Thread(target = self.__read)
            self.readthread.setDaemon(1)
            self.readthread.start()
            return True
        return False
    
    def Stop(self):
        self.alive = False
        self.readthread.join()
            
    def __read(self):
        while self.alive:
            try:
                n = self.serial.inWaiting()
                if n:
                    time.sleep(0.05)
                    n = self.serial.inWaiting()
                    data = self.serial.read(n)
                    if self.CheckData:
                        self.CheckData(data)
                time.sleep(0.1)
            except Exception,ex:
                try:
                    error.traceback()
                except:
                    pass
    